"""Codex审查流程的工作流管理器。"""

import os
import shutil
import asyncio
from pathlib import Path
from datetime import datetime
from typing import Dict, Any

try:
    from .file_generator import FileGenerator
    from .reviewer import CodexReviewer
    from .report_parser import ReportParser
    from .data_models import ReviewResult, ParsedReport
except ImportError:
    from file_generator import FileGenerator
    from reviewer import CodexReviewer
    from report_parser import ReportParser
    from data_models import ReviewResult, ParsedReport


class CodexWorkflowManager:
    """管理完整的Codex审查工作流。"""

    # Session management constants
    DEFAULT_KEEP_SESSIONS = 10  # 保留最近N个session

    def __init__(self, base_dir: str = "ClaudeCodexTasks", project_root: str = None):
        """初始化工作流管理器。

        Args:
            base_dir: 所有session的基础目录（相对于项目根目录）
            project_root: 项目根目录的绝对路径（必需参数）
        """
        if not project_root:
            raise ValueError("project_root is required parameter")

        self.project_root = Path(project_root)
        self.base_dir = self.project_root / base_dir

    async def start_review(
        self,
        review_request_path: str,
        draft_path: str,
        max_iterations: int = 3,
        timeout_seconds: int = 1800
    ) -> ReviewResult:
        """启动Codex审查流程（新API）

        Args:
            review_request_path: ClaudeCode生成的review_request.md临时文件路径
            draft_path: ClaudeCode生成的draft.md临时文件路径
            max_iterations: 最大迭代轮次（默认3，未来扩展）
            timeout_seconds: 超时时间（秒）

        Returns:
            ReviewResult instance with review data and parsed report
        """
        # 1. 创建session目录
        session_dir = self._create_session_dir()

        try:
            # 2. 复制文件到session目录并统一编码
            file_gen = FileGenerator(session_dir)
            review_file, draft_file = file_gen.copy_files_to_session(
                review_request_path, draft_path
            )

            # 3. 启动Codex审查
            reviewer = CodexReviewer(timeout_seconds=timeout_seconds)
            result = await reviewer.start_review(
                session_dir=str(session_dir),
                project_root=str(self.project_root)
            )

            # 4. 解析report.md并重新构造ReviewResult（dataclass不可变）
            if result.status == "completed" and result.report_content:
                parsed = ReportParser.parse_report(result.report_content)
                # 重新构造ReviewResult，使用parsed的status
                result = ReviewResult(
                    status=parsed.status,
                    report_content=result.report_content,
                    log_tail=result.log_tail,
                    execution_time=result.execution_time,
                    parsed=parsed,
                    session_dir=result.session_dir
                )
            else:
                # 解析失败，构造空的parsed
                result = ReviewResult(
                    status=result.status,
                    report_content=result.report_content,
                    log_tail=result.log_tail,
                    execution_time=result.execution_time,
                    parsed=ParsedReport(
                        status=result.status,
                        issues=[],
                        suggestions=[],
                        raw_content=result.report_content
                    ),
                    session_dir=result.session_dir
                )

            return result

        except Exception as e:
            return ReviewResult(
                status="failed",
                report_content="",
                log_tail=f"Error: {str(e)}",
                execution_time=0,
                parsed=ParsedReport(
                    status="failed",
                    issues=[],
                    suggestions=[],
                    raw_content=""
                ),
                session_dir=str(session_dir) if 'session_dir' in locals() else None
            )

    def _cleanup_old_sessions(self, keep_count: int = 10):
        """清理旧的session目录，保留最近N个

        Args:
            keep_count: 保留最近N个session目录（默认10个）
        """
        sessions_dir = self.base_dir / "sessions"
        if not sessions_dir.exists():
            return

        # 获取所有session目录
        session_dirs = [d for d in sessions_dir.iterdir() if d.is_dir() and d.name.startswith("session-")]

        # 按修改时间排序（最新的在前）
        session_dirs.sort(key=lambda d: d.stat().st_mtime, reverse=True)

        # 删除超出保留数量的旧session
        for old_session in session_dirs[keep_count:]:
            try:
                shutil.rmtree(old_session)
            except Exception:
                pass  # 忽略删除失败的情况

    def _create_session_dir(self) -> Path:
        """创建session目录

        Returns:
            创建的session目录路径
        """
        # 清理旧的session目录（保留最近10个）
        self._cleanup_old_sessions(keep_count=self.DEFAULT_KEEP_SESSIONS)

        # Generate timestamp
        timestamp = datetime.now().strftime("%Y%m%d-%H%M%S")

        # Directory path: ClaudeCodexTasks/sessions/session-{timestamp}/
        session_dir = self.base_dir / "sessions" / f"session-{timestamp}"

        # Create directory
        session_dir.mkdir(parents=True, exist_ok=True)

        return session_dir

    def cleanup_session(self, session_dir: str) -> bool:
        """清理session目录

        Args:
            session_dir: Session目录路径

        Returns:
            True表示清理成功，False表示失败
        """
        try:
            import shutil
            shutil.rmtree(session_dir)
            return True
        except Exception:
            return False
